/**
 * losenote.com Inc.
 * Copyright (c) 2013-2013 All Rights Reserved.
 */
package com.losenote.service.impl;

import org.apache.commons.lang.StringUtils;
import com.losenote.base.LnException;
import com.losenote.base.template.AbstractServiceImpl;
import com.losenote.base.template.BlankCallback;
import com.losenote.core.ContactDetailComponent;
import com.losenote.core.QuestionComponent;
import com.losenote.model.ContactDetail;
import com.losenote.model.Question;
import com.losenote.service.QuestionService;
import com.losenote.service.req.AnswerReq;
import com.losenote.service.result.AnswerResult;

/**
 * 问题验证服务
 * 
 * @author danjingyu
 * @version $Id: QuestionServiceImpl.java, v 0.1 2013-11-1 上午8:29:48 danjingyu Exp $
 */
public class QuestionServiceImpl extends AbstractServiceImpl implements QuestionService {

    /**联系信息组件*/
    private ContactDetailComponent contactDetailComponent;

    /**用户操作组件*/
    private QuestionComponent      questionComponent;

    /** 
     * @see com.losenote.service.QuestionService#validQuestion(java.util.List)
     */
    @Override
    public AnswerResult validQuestion(final AnswerReq answerReq) {
        return serviceTemplate.execute(AnswerResult.class, new BlankCallback() {

            /**
             * 基本校验
             * @see com.losenote.base.template.BlankCallback#check()
             */
            public void check() {
                //AssertUtil.notBlank(answerReq.getAnswer(), "验证失败，答案为空!");
            }

            /**
             * 服务操作
             * @see com.losenote.base.template.BlankCallback#executeService()
             */
            public AnswerResult executeService() {

                for (int index = 0; index < answerReq.getQuestionIds().size(); index++) {
                    //【1】读取问题
                    Question question = questionComponent.queryById(answerReq.getQuestionIds().get(
                        index));
                    String answer = answerReq.getAnswers().get(index);
                    //【2】对比问题
                    if (!StringUtils.equals(question.getAnswer(), answer)) {
                        throw new LnException("问题答案不正确，无法验证");
                    }
                }

                //【3】獲取聯繫方式
                ContactDetail contactDetail = contactDetailComponent.getById(answerReq
                    .getContactId());
                return new AnswerResult(contactDetail);
            }

        });
    }

    public void setContactDetailComponent(ContactDetailComponent contactDetailComponent) {
        this.contactDetailComponent = contactDetailComponent;
    }

    public void setQuestionComponent(QuestionComponent questionComponent) {
        this.questionComponent = questionComponent;
    }

}
